// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  
  try {
    // 生成6位随机房间号
    const roomId = Math.floor(100000 + Math.random() * 900000).toString()
    
    // 创建房间
    const roomData = {
      roomId: roomId,
      creator: wxContext.OPENID,
      players: [{
        openid: wxContext.OPENID,
        nickName: event.nickName,
        avatarUrl: event.avatarUrl,
        isReady: false
      }],
      maxPlayers: 2,
      status: 'waiting', // waiting, playing, finished
      createTime: db.serverDate(),
      lastUpdateTime: db.serverDate(),
      gameData: {
        currentRound: 0,
        totalRounds: 10,
        currentPlayer: null,
        questions: [],
        results: []
      }
    }
    
    // 检查房间号是否已存在
    const existRoom = await db.collection('rooms').where({
      roomId: roomId
    }).get()
    
    if (existRoom.data.length > 0) {
      return {
        success: false,
        error: '房间号已存在，请重试'
      }
    }
    
    // 创建房间
    const result = await db.collection('rooms').add({
      data: roomData
    })
    
    return {
      success: true,
      roomId: roomId,
      roomData: roomData
    }
  } catch (error) {
    console.error('创建房间失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 